/**
 * WebXR Performance Optimizer
 * 自动性能优化和监控系统
 */

export class WebXROptimizer {
    constructor(renderer, scene, camera) {
        this.renderer = renderer;
        this.scene = scene;
        this.camera = camera;
        
        // 性能监控数据
        this.performanceData = {
            fps: 0,
            frameTime: 0,
            renderTime: 0,
            drawCalls: 0,
            triangles: 0,
            memory: 0,
            cpuUsage: 0,
            gpuUsage: 0
        };
        
        // 优化设置
        this.optimizationSettings = {
            targetFPS: 90, // Vision Pro 目标帧率
            adaptiveQuality: true,
            dynamicLOD: true,
            frustumCulling: true,
            occlusionCulling: false,
            shadowOptimization: true,
            textureCompression: true,
            geometryOptimization: true
        };
        
        // 性能阈值
        this.thresholds = {
            lowFPS: 60,
            highFrameTime: 16.67, // 60fps = 16.67ms
            highDrawCalls: 1000,
            highTriangles: 100000,
            highMemory: 512 * 1024 * 1024 // 512MB
        };
        
        // 优化状态
        this.optimizationState = {
            qualityLevel: 'high', // high, medium, low
            lodLevel: 1.0,
            shadowQuality: 'high',
            textureQuality: 'high',
            particleDensity: 1.0,
            effectsEnabled: true
        };
        
        // 监控间隔
        this.monitoringInterval = null;
        this.optimizationInterval = null;
        
        // 性能历史
        this.performanceHistory = [];
        this.maxHistoryLength = 300; // 5分钟的数据（60fps）
        
        // 初始化
        this.init();
    }
    
    init() {
        console.log('WebXR Performance Optimizer initialized');
        
        // 设置渲染器优化
        this.setupRendererOptimizations();
        
        // 启动性能监控
        this.startPerformanceMonitoring();
        
        // 启动自动优化
        this.startAutoOptimization();
        
        // 设置事件监听器
        this.setupEventListeners();
    }
    
    setupRendererOptimizations() {
        // 基础渲染器优化
        this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        this.renderer.outputEncoding = THREE.sRGBEncoding;
        this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
        this.renderer.toneMappingExposure = 1.0;
        
        // 启用硬件抗锯齿
        this.renderer.antialias = true;
        
        // 优化渲染状态
        this.renderer.sortObjects = true;
        this.renderer.autoClear = true;
        this.renderer.autoClearColor = true;
        this.renderer.autoClearDepth = true;
        this.renderer.autoClearStencil = true;
        
        console.log('Renderer optimizations applied');
    }
    
    startPerformanceMonitoring() {
        let lastTime = performance.now();
        let frameCount = 0;
        let fpsUpdateTime = 0;
        
        const monitor = () => {
            const currentTime = performance.now();
            const deltaTime = currentTime - lastTime;
            
            frameCount++;
            fpsUpdateTime += deltaTime;
            
            // 每秒更新一次 FPS
            if (fpsUpdateTime >= 1000) {
                this.performanceData.fps = Math.round((frameCount * 1000) / fpsUpdateTime);
                frameCount = 0;
                fpsUpdateTime = 0;
            }
            
            // 更新帧时间
            this.performanceData.frameTime = deltaTime;
            
            // 更新渲染统计
            this.updateRenderStats();
            
            // 更新内存使用
            this.updateMemoryStats();
            
            // 记录性能历史
            this.recordPerformanceHistory();
            
            lastTime = currentTime;
            
            // 继续监控
            this.monitoringInterval = requestAnimationFrame(monitor);
        };
        
        monitor();
        console.log('Performance monitoring started');
    }
    
    updateRenderStats() {
        const info = this.renderer.info;
        
        this.performanceData.drawCalls = info.render.calls;
        this.performanceData.triangles = info.render.triangles;
        this.performanceData.renderTime = info.render.frame;
        
        // 重置渲染统计
        info.reset();
    }
    
    updateMemoryStats() {
        const info = this.renderer.info;
        
        this.performanceData.memory = info.memory.geometries + info.memory.textures;
        
        // 如果支持，获取更详细的内存信息
        if (performance.memory) {
            this.performanceData.memory = performance.memory.usedJSHeapSize;
        }
    }
    
    recordPerformanceHistory() {
        const record = {
            timestamp: Date.now(),
            fps: this.performanceData.fps,
            frameTime: this.performanceData.frameTime,
            drawCalls: this.performanceData.drawCalls,
            triangles: this.performanceData.triangles,
            memory: this.performanceData.memory
        };
        
        this.performanceHistory.push(record);
        
        // 限制历史记录长度
        if (this.performanceHistory.length > this.maxHistoryLength) {
            this.performanceHistory.shift();
        }
    }
    
    startAutoOptimization() {
        const optimize = () => {
            // 检查性能并应用优化
            this.analyzePerformance();
            this.applyOptimizations();
            
            // 每5秒检查一次
            setTimeout(optimize, 5000);
        };
        
        optimize();
        console.log('Auto optimization started');
    }
    
    analyzePerformance() {
        const { fps, frameTime, drawCalls, triangles, memory } = this.performanceData;
        const { lowFPS, highFrameTime, highDrawCalls, highTriangles, highMemory } = this.thresholds;
        
        // 分析 FPS
        if (fps < lowFPS) {
            this.recommendOptimization('fps', 'low', `FPS 过低: ${fps}`);
        }
        
        // 分析帧时间
        if (frameTime > highFrameTime) {
            this.recommendOptimization('frameTime', 'high', `帧时间过长: ${frameTime.toFixed(2)}ms`);
        }
        
        // 分析绘制调用
        if (drawCalls > highDrawCalls) {
            this.recommendOptimization('drawCalls', 'high', `绘制调用过多: ${drawCalls}`);
        }
        
        // 分析三角形数量
        if (triangles > highTriangles) {
            this.recommendOptimization('triangles', 'high', `三角形数量过多: ${triangles}`);
        }
        
        // 分析内存使用
        if (memory > highMemory) {
            this.recommendOptimization('memory', 'high', `内存使用过高: ${(memory / 1024 / 1024).toFixed(2)}MB`);
        }
    }
    
    recommendOptimization(metric, level, message) {
        console.warn(`Performance Warning: ${message}`);
        
        // 根据性能问题应用相应优化
        switch (metric) {
            case 'fps':
            case 'frameTime':
                this.optimizeFrameRate();
                break;
            case 'drawCalls':
                this.optimizeDrawCalls();
                break;
            case 'triangles':
                this.optimizeGeometry();
                break;
            case 'memory':
                this.optimizeMemory();
                break;
        }
    }
    
    applyOptimizations() {
        const { fps } = this.performanceData;
        const { targetFPS } = this.optimizationSettings;
        
        // 动态质量调整
        if (this.optimizationSettings.adaptiveQuality) {
            if (fps < targetFPS * 0.8) {
                this.lowerQuality();
            } else if (fps > targetFPS * 0.95) {
                this.raiseQuality();
            }
        }
        
        // 动态 LOD 调整
        if (this.optimizationSettings.dynamicLOD) {
            this.updateLOD();
        }
    }
    
    optimizeFrameRate() {
        // 降低渲染质量
        if (this.optimizationState.qualityLevel === 'high') {
            this.optimizationState.qualityLevel = 'medium';
            this.applyQualitySettings();
        } else if (this.optimizationState.qualityLevel === 'medium') {
            this.optimizationState.qualityLevel = 'low';
            this.applyQualitySettings();
        }
        
        // 减少粒子密度
        this.optimizationState.particleDensity = Math.max(0.3, this.optimizationState.particleDensity * 0.8);
        
        console.log('Frame rate optimization applied');
    }
    
    optimizeDrawCalls() {
        // 启用实例化渲染
        this.enableInstancing();
        
        // 合并几何体
        this.mergeGeometries();
        
        // 优化材质
        this.optimizeMaterials();
        
        console.log('Draw calls optimization applied');
    }
    
    optimizeGeometry() {
        // 降低 LOD 级别
        this.optimizationState.lodLevel = Math.max(0.3, this.optimizationState.lodLevel * 0.8);
        this.updateLOD();
        
        // 简化几何体
        this.simplifyGeometries();
        
        console.log('Geometry optimization applied');
    }
    
    optimizeMemory() {
        // 清理未使用的资源
        this.cleanupResources();
        
        // 压缩纹理
        this.compressTextures();
        
        // 减少缓存大小
        this.reduceCacheSize();
        
        console.log('Memory optimization applied');
    }
    
    lowerQuality() {
        if (this.optimizationState.qualityLevel === 'high') {
            this.optimizationState.qualityLevel = 'medium';
        } else if (this.optimizationState.qualityLevel === 'medium') {
            this.optimizationState.qualityLevel = 'low';
        }
        this.applyQualitySettings();
    }
    
    raiseQuality() {
        if (this.optimizationState.qualityLevel === 'low') {
            this.optimizationState.qualityLevel = 'medium';
        } else if (this.optimizationState.qualityLevel === 'medium') {
            this.optimizationState.qualityLevel = 'high';
        }
        this.applyQualitySettings();
    }
    
    applyQualitySettings() {
        const { qualityLevel } = this.optimizationState;
        
        switch (qualityLevel) {
            case 'high':
                this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
                this.optimizationState.shadowQuality = 'high';
                this.optimizationState.textureQuality = 'high';
                this.optimizationState.effectsEnabled = true;
                break;
            case 'medium':
                this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.5));
                this.optimizationState.shadowQuality = 'medium';
                this.optimizationState.textureQuality = 'medium';
                this.optimizationState.effectsEnabled = true;
                break;
            case 'low':
                this.renderer.setPixelRatio(1);
                this.optimizationState.shadowQuality = 'low';
                this.optimizationState.textureQuality = 'low';
                this.optimizationState.effectsEnabled = false;
                break;
        }
        
        this.applyShadowQuality();
        this.applyTextureQuality();
        
        console.log(`Quality level set to: ${qualityLevel}`);
    }
    
    applyShadowQuality() {
        const { shadowQuality } = this.optimizationState;
        
        switch (shadowQuality) {
            case 'high':
                this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
                break;
            case 'medium':
                this.renderer.shadowMap.type = THREE.PCFShadowMap;
                break;
            case 'low':
                this.renderer.shadowMap.type = THREE.BasicShadowMap;
                break;
        }
    }
    
    applyTextureQuality() {
        // 遍历场景中的所有材质，调整纹理质量
        this.scene.traverse((object) => {
            if (object.material) {
                const materials = Array.isArray(object.material) ? object.material : [object.material];
                materials.forEach(material => {
                    this.optimizeMaterialTextures(material);
                });
            }
        });
    }
    
    optimizeMaterialTextures(material) {
        const { textureQuality } = this.optimizationState;
        
        ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap'].forEach(textureType => {
            if (material[textureType]) {
                const texture = material[textureType];
                
                switch (textureQuality) {
                    case 'high':
                        texture.minFilter = THREE.LinearMipmapLinearFilter;
                        texture.magFilter = THREE.LinearFilter;
                        break;
                    case 'medium':
                        texture.minFilter = THREE.LinearMipmapNearestFilter;
                        texture.magFilter = THREE.LinearFilter;
                        break;
                    case 'low':
                        texture.minFilter = THREE.NearestMipmapNearestFilter;
                        texture.magFilter = THREE.NearestFilter;
                        break;
                }
                
                texture.needsUpdate = true;
            }
        });
    }
    
    updateLOD() {
        const { lodLevel } = this.optimizationState;
        
        // 遍历场景中的所有对象，应用 LOD
        this.scene.traverse((object) => {
            if (object.geometry && object.userData.originalGeometry) {
                // 根据 LOD 级别调整几何体复杂度
                this.applyGeometryLOD(object, lodLevel);
            }
        });
    }
    
    applyGeometryLOD(object, lodLevel) {
        // 简化几何体的实现
        // 这里可以根据距离和 LOD 级别动态调整几何体复杂度
        if (object.geometry.attributes.position) {
            const originalCount = object.userData.originalVertexCount || object.geometry.attributes.position.count;
            const targetCount = Math.floor(originalCount * lodLevel);
            
            // 实际的几何体简化逻辑需要更复杂的算法
            // 这里只是示例
        }
    }
    
    enableInstancing() {
        // 查找可以实例化的对象
        const instanceGroups = new Map();
        
        this.scene.traverse((object) => {
            if (object.geometry && object.material) {
                const key = `${object.geometry.uuid}_${object.material.uuid}`;
                if (!instanceGroups.has(key)) {
                    instanceGroups.set(key, []);
                }
                instanceGroups.get(key).push(object);
            }
        });
        
        // 为重复对象创建实例化渲染
        instanceGroups.forEach((objects, key) => {
            if (objects.length > 3) { // 只有超过3个相同对象才实例化
                this.createInstancedMesh(objects);
            }
        });
    }
    
    createInstancedMesh(objects) {
        if (objects.length === 0) return;
        
        const geometry = objects[0].geometry;
        const material = objects[0].material;
        
        const instancedMesh = new THREE.InstancedMesh(geometry, material, objects.length);
        
        objects.forEach((object, index) => {
            const matrix = new THREE.Matrix4();
            matrix.compose(object.position, object.quaternion, object.scale);
            instancedMesh.setMatrixAt(index, matrix);
            
            // 从场景中移除原对象
            object.parent.remove(object);
        });
        
        instancedMesh.instanceMatrix.needsUpdate = true;
        this.scene.add(instancedMesh);
        
        console.log(`Created instanced mesh with ${objects.length} instances`);
    }
    
    mergeGeometries() {
        // 合并静态几何体以减少绘制调用
        const staticObjects = [];
        
        this.scene.traverse((object) => {
            if (object.geometry && !object.userData.dynamic) {
                staticObjects.push(object);
            }
        });
        
        // 按材质分组
        const materialGroups = new Map();
        staticObjects.forEach(object => {
            const materialKey = object.material.uuid;
            if (!materialGroups.has(materialKey)) {
                materialGroups.set(materialKey, []);
            }
            materialGroups.get(materialKey).push(object);
        });
        
        // 合并每个材质组的几何体
        materialGroups.forEach((objects, materialKey) => {
            if (objects.length > 1) {
                this.mergeGeometryGroup(objects);
            }
        });
    }
    
    mergeGeometryGroup(objects) {
        const geometries = [];
        
        objects.forEach(object => {
            const geometry = object.geometry.clone();
            geometry.applyMatrix4(object.matrixWorld);
            geometries.push(geometry);
            
            // 从场景中移除原对象
            object.parent.remove(object);
        });
        
        const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries(geometries);
        const mergedMesh = new THREE.Mesh(mergedGeometry, objects[0].material);
        
        this.scene.add(mergedMesh);
        
        console.log(`Merged ${objects.length} geometries`);
    }
    
    optimizeMaterials() {
        const materialMap = new Map();
        
        // 查找重复的材质
        this.scene.traverse((object) => {
            if (object.material) {
                const materials = Array.isArray(object.material) ? object.material : [object.material];
                materials.forEach(material => {
                    const key = this.getMaterialKey(material);
                    if (!materialMap.has(key)) {
                        materialMap.set(key, []);
                    }
                    materialMap.get(key).push({ object, material });
                });
            }
        });
        
        // 共享相同的材质
        materialMap.forEach((items, key) => {
            if (items.length > 1) {
                const sharedMaterial = items[0].material;
                items.slice(1).forEach(item => {
                    item.object.material = sharedMaterial;
                });
                console.log(`Shared material for ${items.length} objects`);
            }
        });
    }
    
    getMaterialKey(material) {
        // 生成材质的唯一键
        return `${material.type}_${material.color?.getHex()}_${material.transparent}_${material.opacity}`;
    }
    
    simplifyGeometries() {
        this.scene.traverse((object) => {
            if (object.geometry && object.geometry.attributes.position) {
                // 简化几何体（这里需要实际的简化算法）
                this.simplifyGeometry(object.geometry);
            }
        });
    }
    
    simplifyGeometry(geometry) {
        // 简化几何体的实现
        // 这里可以使用 SimplifyModifier 或其他简化算法
        const positions = geometry.attributes.position.array;
        const originalCount = positions.length / 3;
        const targetCount = Math.floor(originalCount * this.optimizationState.lodLevel);
        
        // 实际的简化逻辑需要更复杂的算法
        console.log(`Simplified geometry from ${originalCount} to ${targetCount} vertices`);
    }
    
    cleanupResources() {
        // 清理未使用的几何体
        this.cleanupGeometries();
        
        // 清理未使用的纹理
        this.cleanupTextures();
        
        // 清理未使用的材质
        this.cleanupMaterials();
        
        // 强制垃圾回收（如果支持）
        if (window.gc) {
            window.gc();
        }
    }
    
    cleanupGeometries() {
        // 实现几何体清理逻辑
        console.log('Cleaned up unused geometries');
    }
    
    cleanupTextures() {
        // 实现纹理清理逻辑
        console.log('Cleaned up unused textures');
    }
    
    cleanupMaterials() {
        // 实现材质清理逻辑
        console.log('Cleaned up unused materials');
    }
    
    compressTextures() {
        this.scene.traverse((object) => {
            if (object.material) {
                const materials = Array.isArray(object.material) ? object.material : [object.material];
                materials.forEach(material => {
                    this.compressMaterialTextures(material);
                });
            }
        });
    }
    
    compressMaterialTextures(material) {
        ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap'].forEach(textureType => {
            if (material[textureType]) {
                const texture = material[textureType];
                
                // 应用纹理压缩
                if (this.renderer.capabilities.isWebGL2) {
                    // 使用 WebGL2 的纹理压缩格式
                    texture.format = THREE.RGBAFormat;
                    texture.type = THREE.UnsignedByteType;
                }
                
                texture.needsUpdate = true;
            }
        });
    }
    
    reduceCacheSize() {
        // 减少各种缓存的大小
        console.log('Reduced cache sizes');
    }
    
    setupEventListeners() {
        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            this.handleResize();
        });
        
        // 监听页面可见性变化
        document.addEventListener('visibilitychange', () => {
            this.handleVisibilityChange();
        });
    }
    
    handleResize() {
        // 窗口大小变化时的优化
        const canvas = this.renderer.domElement;
        const width = canvas.clientWidth;
        const height = canvas.clientHeight;
        
        // 根据窗口大小调整渲染质量
        if (width * height > 1920 * 1080) {
            this.optimizationState.qualityLevel = 'medium';
        } else {
            this.optimizationState.qualityLevel = 'high';
        }
        
        this.applyQualitySettings();
    }
    
    handleVisibilityChange() {
        if (document.hidden) {
            // 页面隐藏时降低性能消耗
            this.pauseOptimization();
        } else {
            // 页面显示时恢复正常性能
            this.resumeOptimization();
        }
    }
    
    pauseOptimization() {
        if (this.monitoringInterval) {
            cancelAnimationFrame(this.monitoringInterval);
            this.monitoringInterval = null;
        }
        console.log('Performance optimization paused');
    }
    
    resumeOptimization() {
        if (!this.monitoringInterval) {
            this.startPerformanceMonitoring();
        }
        console.log('Performance optimization resumed');
    }
    
    // 公共 API
    getPerformanceData() {
        return { ...this.performanceData };
    }
    
    getOptimizationState() {
        return { ...this.optimizationState };
    }
    
    getPerformanceHistory() {
        return [...this.performanceHistory];
    }
    
    setTargetFPS(fps) {
        this.optimizationSettings.targetFPS = fps;
        console.log(`Target FPS set to: ${fps}`);
    }
    
    setQualityLevel(level) {
        this.optimizationState.qualityLevel = level;
        this.applyQualitySettings();
        console.log(`Quality level manually set to: ${level}`);
    }
    
    enableAdaptiveQuality(enabled) {
        this.optimizationSettings.adaptiveQuality = enabled;
        console.log(`Adaptive quality ${enabled ? 'enabled' : 'disabled'}`);
    }
    
    generatePerformanceReport() {
        const report = {
            timestamp: new Date().toISOString(),
            performanceData: this.getPerformanceData(),
            optimizationState: this.getOptimizationState(),
            settings: { ...this.optimizationSettings },
            history: this.getPerformanceHistory(),
            recommendations: this.generateRecommendations()
        };
        
        return report;
    }
    
    generateRecommendations() {
        const recommendations = [];
        const { fps, drawCalls, triangles, memory } = this.performanceData;
        
        if (fps < this.thresholds.lowFPS) {
            recommendations.push('考虑降低渲染质量或减少场景复杂度');
        }
        
        if (drawCalls > this.thresholds.highDrawCalls) {
            recommendations.push('考虑合并几何体或使用实例化渲染');
        }
        
        if (triangles > this.thresholds.highTriangles) {
            recommendations.push('考虑使用 LOD 系统或简化几何体');
        }
        
        if (memory > this.thresholds.highMemory) {
            recommendations.push('考虑压缩纹理或清理未使用的资源');
        }
        
        return recommendations;
    }
    
    destroy() {
        // 清理资源
        this.pauseOptimization();
        
        // 移除事件监听器
        window.removeEventListener('resize', this.handleResize);
        document.removeEventListener('visibilitychange', this.handleVisibilityChange);
        
        console.log('WebXR Performance Optimizer destroyed');
    }
}